package primary.code06_graph;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 有向图，第一个元素代表权值，第二个元素代表一条边的出边节点，第三个元素代表一条边的入边节点
 *
 * @author Yudi Wang
 * @date 2021/7/16 11:10
 * 将任意图结构转化为熟悉的图结构
 */
public class Code01_GraphTransferStructure {

    private static Graph transferGraph(int[][] arr) {
        final Graph graph = new Graph(new HashMap<>(), new ArrayList<>());
        for (int[] ints : arr) {
            if (!graph.nodes.containsKey(ints[1])) {
                graph.nodes.put(ints[1], new Node(ints[1]));
            }
            if (!graph.nodes.containsKey(ints[2])) {
                graph.nodes.put(ints[2], new Node(ints[2]));
            }
            Node from = graph.nodes.get(ints[1]);
            Node to = graph.nodes.get(ints[2]);
            Edge edge = new Edge(from, to, ints[0]);
            graph.edges.add(edge);
            from.out++;
            to.in++;
            from.edges.add(edge);
            from.next.add(to);
        }
        return graph;
    }


    private static Graph transferGraphTest(int[][] arr) {
        Graph graph = new Graph(new HashMap<Integer, Node>(), new ArrayList<Edge>());
        for (int[] row : arr) {
            int weight = row[0];
            Node from = graph.nodes.get(row[1]) == null ? new Node(row[1]) : graph.nodes.get(row[1]);
            Node to = graph.nodes.get(row[2]) == null ? new Node(row[2]) : graph.nodes.get(row[2]);
            Edge edge = new Edge(from, to, weight);
            graph.edges.add(edge); // edges
            from.out++;
            from.edges.add(edge);
            from.next.add(to);
            to.in++;
            graph.nodes.put(from.val, from);
            graph.nodes.put(to.val, to);
        }
        return graph;
    }

    public static void main(String[] args) {
        //第一个元素代表权值，第二个元素代表一条边的出边节点，第三个元素代表一条边的入边节点
        int[][] arr = {
                {4, 1, 2},
                {2, 1, 3},
                {3, 2, 3},
                {1, 3, 1}};
        Graph g = transferGraph(arr);
        System.out.println(g);
        Graph g2 = transferGraphTest(arr);
        System.out.println(g2);
    }
}
